package com.topInterview;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: huangzhigao
 * @Date: 2022/2/20 14:37
 */
public class leecode54_printEdge {
    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int tr = 0;
        int tc = 0;
        int dr = matrix.length-1;
        int dc = matrix[0].length-1;
        while (tr <= dr && tc <= dc) {
            print(matrix, tr++, tc++, dr--, dc--, res);
        }

        return res;
    }


    public static void print(int[][] matrix, int a, int b, int c, int d, List<Integer> res) {
        if (a == c) {
            //只剩一行
            for (int i = b; i <= d; i++) {
                res.add(matrix[a][i]);
            }
        } else if (b == d) {
            //只剩一列
            for (int i = a; i <= c; i++) {
                res.add(matrix[i][b]);
            }
        } else {
            int curR = a;
            int curC = b;
            while (curC != d) {
                res.add(matrix[a][curC++]);
            }
            while (curR != c) {
                res.add(matrix[curR++][d]);
            }

            while (curC!=b){
                res.add(matrix[c][curC--]);
            }
            while (curR!=a){
                res.add(matrix[curR--][b]);
            }
        }
    }

    public static void main(String[] args) {
        int[][] res = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        spiralOrder(res);
    }
}
